package web.controller;

import hibernate.pojo.User;
import hibernate.util.HibernateUtil;

import java.io.Serializable;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.jbpm.api.Configuration;
import org.jbpm.api.Execution;
import org.jbpm.api.ExecutionService;
import org.jbpm.api.ProcessEngine;
import org.jbpm.api.ProcessInstance;

public class LoginController {

	private static final Log logger = LogFactory.getLog(LoginController.class);

	public LoginController() {
		// TODO Auto-generated constructor stub
	}

	private String userName;
	private String password;
	private User user; 

	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}

	public String authenticateUser(){
		System.out.println("Login Clicked!");

//		ProcessEngine processEngine = Configuration.getProcessEngine();
//		ExecutionService executionService = processEngine.getExecutionService();
//		Map<String, Object> variables = new HashMap<String, Object>();
//	    variables.put("hand", new Hand());
//	    variables.put("joesmoe", new JoeSmoe());
//	    
//	    ProcessInstance processInstance = executionService.startProcessInstanceByKey("Java", variables);
//	    String pid = processInstance.getId();
//	    
//	    String answer = (String) executionService.getVariable(pid, "answer");
//	    System.out.println(""+answer);
//	    Hand hand = (Hand) executionService.getVariable(pid, "hand");
//	    boolean result = hand.isShaken();
		
		//working block!!! TG
//		ProcessInstance processInstance = executionService.startProcessInstanceByKey("Custom");
//		String processInstanceId = processInstance.getId();
//		System.out.println("Process instance id : "+processInstanceId);
//		
//	    Execution executiongeneratepdf = processInstance.findActiveExecutionIn("print dots");
//	    String executionId = executiongeneratepdf.getId();
//	    executionService.signalExecutionById(executionId);
//		
		String returnString ="";
		User user = null ;

		try {
//			Criteria criteria = HibernateUtil.getSessionFactory().openSession().createCriteria(User.class);
//			criteria.add(Restrictions.eq("userName",userName));
//			criteria.add(Restrictions.eq("password",password));
//
//			List<User> users = criteria.list();
//			if( users!= null && users.size() == 1) {
//				user = (User)criteria.list().get(0);
//				setUser(user);
//				FacesContext context = FacesContext.getCurrentInstance();
//				context.getExternalContext().getSessionMap().put("user", user);
//
//				returnString = "success";
//			}
//			else {
//				ensureAddErrorMessage("Error on login!");
//				returnString = "failure";
//			}
			returnString = "success";
		} catch (Exception exception) {
			logger.error("Login Hatasi olustu!", exception);
			//System.out.println("Exception occured : "+e.toString());
		}
		//		UserDao userDao = new HibernateUserDaoImpl();
		//		User user = userDao.findUser(getUserName(),getPassword());
		return returnString;
	}

	public String register() {
		return "register";
	}

	public String forgotpassword() {
		return "forgotpassword";
	}
	public String logout(){

		System.out.println("Logout Clicked!");
		logger.debug("Logout Clicked! ");

		FacesContext context = FacesContext.getCurrentInstance();
		HttpSession session = (HttpSession) context.getExternalContext().getSession(true);
		if(session==null){
			return "invalid";
		}
		else{
			session.invalidate();
			return "logoutSuccess";
		}
	}
	public void setUser(User user) {
		this.user = user;
	}
	public User getUser() {
		return user;
	}  
	
    private void ensureAddErrorMessage(Exception ex, String defaultMsg) {
        String msg = ex.getLocalizedMessage();
        if (msg != null && msg.length() > 0) {
            addErrorMessage(msg);
        } else {
            addErrorMessage(defaultMsg);
        }
    }

    private void ensureAddErrorMessage(String defaultMsg) {
        if (defaultMsg != null && defaultMsg.length() > 0) {
            addErrorMessage(defaultMsg);
        }
    }
    
    public static void addErrorMessage(String msg) {
        FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, msg);
        FacesContext.getCurrentInstance().addMessage(null, facesMsg);
    }

    public static void addSuccessMessage(String msg) {
        FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_INFO, msg, msg);
        FacesContext.getCurrentInstance().addMessage("successInfo", facesMsg);
    }
    
}
